<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/15 0015
 * Time: 下午 5:55
 */
namespace app\api\controller;

use app\admin\model\Store;
use app\api\service\GroupRefund;
use app\common\model\Groupdetail;
use app\common\model\Groupproduct;
use app\common\model\User;
use app\common\validate\GroupList;
use app\api\service\Token as TokenService;
use app\common\validate\IDMustBePostiveInt;
use app\common\validate\MakeGroup;
use app\common\validate\myGroupDetails;
use app\lib\exception\ParameterException;
use app\api\service\Group as GroupService;
use think\Db;
use think\Request;

class Group extends BaseController{

    /**
     * 获取商家门店的拼团列表
     * @return \think\response\Json
     * @throws ParameterException
     */
    public function GroupList(){
        //需要参数门店id
        (new GroupList())->goCheck();
        $tenantid = TokenService::getTenantid();
        $store = Store::get(input('post.storeId'));
        if($store->tenantId != $tenantid){
            throw new ParameterException([
                'msg' => '门店与商户不匹配'
            ]);
        }
        $grouplist = Groupproduct::where(['storeId'=>input('post.storeId'),'status'=>1])->order('create_time desc')->field('a.id,a.status,b.imgUrl,b.title,b.currentPrice,b.groupPrice,b.id productId,a.groupSuccCount')->alias('a')->join('product b','a.productId=b.id')->select();
//        foreach ($grouplist as $value){
//            //取出关联的商品信息
//            $value->product;
//        }
        if(!$grouplist){
            return show(config('status.ERROR_STATUS'),'暂无团购活动','');
        }
        return show(config('status.SUCCESS_STATUS'),'ok',$grouplist);



    }

    /**
     * 团的详情
     * @return \think\response\Json
     * @throws ParameterException
     */
    public function GroupDetails(){
        (new IDMustBePostiveInt())->goCheck();
        $uid = TokenService::getCurrentUid();
        $group = Groupproduct::get(input('post.id'));
        if($group->status!=1){
            throw new ParameterException([
                'msg' => '此拼团已经下架'
            ]);
        }

        $group->product->productdetail;
        $images = Db::table('productdtlimg')->where(['productId' => $group->productId])->field('imgUrl')->select();
        $group->product->images = array_column($images, 'imgUrl');

        $groupdetailmodel = new Groupdetail();
        //我是否正在开/参此团
        $mygroup = $groupdetailmodel->where(['userId'=>$uid,'groupId'=>$group->id,'status'=>1,'isActive'=>1])->find();
        if(!$mygroup){
            $group['ismygroup'] = 0;
        }else{
            $group['ismygroup'] = 1;
        }
        $time = time();
        $groupdetail = $groupdetailmodel->where('status',1)->where(['groupId'=>$group->id,'isActive'=>1,'storeId'=>$group->storeId])->where('endDate','>',$time)->select();

        if($groupdetail){
            $coloneusers = $this->getcolone($groupdetail,$group->id);

            $group->groupdetail = $coloneusers;
        }
        return show(config('status.SUCCESS_STATUS'),'ok',$group);
    }

    /**
     * 获取某个拼团下的团长userid
     * @param $groupdetail
     * @return array
     */
    private function getcolone($groupdetail,$groupId){
        $colonelIDs = [];
        $unigroupIds = [];
        foreach ($groupdetail as $value){
            if($value['userId'] == $value['originator']){
                //开团的用户（团长）
                array_push($colonelIDs,$value['userId']);
                array_push($unigroupIds,$value['unigroupId']);
            }
        }
        $user = User::all($colonelIDs);
        $unigroups = Groupdetail::all($unigroupIds);
        $Groupproduct = Groupproduct::get($groupId);
        $groupnum = $Groupproduct->groupSuccCount;
        foreach ($unigroups as &$v){
            foreach ($user as $value){
                if($v['userId'] == $value['id']){
                    $v['user'] = $value;
                    $unis = Groupdetail::where(['unigroupId'=>$v['unigroupId'],'isActive'=>1])->select();
                    $v['shengyu'] = $groupnum - count($unis);  //当前团还剩人数
                }
            }
        }
        return $unigroups;
    }


    /**
     * 用户开团或参团
     * @return array|\think\response\Json
     * @throws ParameterException
     */
    public function MakeGroup(){
        //参数 1.商户团id,2.团购方式
        //先判断此团用户是否正在参与
        (new MakeGroup())->goCheck();
        $products = input('post.products/a');
        $uid = TokenService::getCurrentUid();
        $orderdata= input('post.');
        unset($orderdata['products']);
        $makegroup = new GroupService();
        $status = $makegroup->makegroup($uid,$orderdata,$products);
        return show(config('status.SUCCESS_STATUS'), '创建团购订单成功', $status);

    }

    /**
     * 我的拼团列表
     * @return \think\response\Json
     */
    public function myGroups(){
        $uid = TokenService::getCurrentUid();
        $GroupdetailModel = new Groupdetail();
        $param = Request::instance()->param();
        $Groupdetail = $GroupdetailModel->where('status',['=',1],['=',2],['=',3],'OR')->where(['userId'=>$uid,'isActive'=>1])->order('create_time desc')->select();
        foreach ($Groupdetail as $value){
            $Groupproduct = Groupproduct::get($value->groupId);
            $value->groupproduct = $Groupproduct;
            $value->groupproduct->product;
        }
        foreach ($Groupdetail as &$value){
            $groups = $GroupdetailModel->where(['unigroupId'=>$value['unigroupId'],'isActive'=>1])->select();
            $value['shengyu'] = $value->groupproduct->groupSuccCount - count($groups);
        }
        if($Groupdetail){
            return show(config('status.SUCCESS_STATUS'),'ok',$Groupdetail);
        }else{
            return show(config('status.ERROR_STATUS'),'您没有参加过团购','');
        }

    }

    /**
     * 拼团详情
     * @return \think\response\Json
     */
    public function myGroupDetails(){
        //参数unigroupId
        (new myGroupDetails())->goCheck();
        $uid = TokenService::getCurrentUid();
        $groupdetail = Groupdetail::where(['unigroupId'=>input('post.unigroupId'),'userId'=>$uid,'isActive'=>1])->find();
        if(!$groupdetail){
            return show(config('status.ERROR_STATUS'),'此团购不存在','此团购不存在');
        }else{
            $group = Groupproduct::get($groupdetail->groupId);
            $group->totalGroup = 20;  //本团此件商品总数量
            $group->product->productdetail;
            $images = Db::table('productdtlimg')->where(['productId' => $group->productId])->field('imgUrl')->select();
            $group->product->images = array_column($images, 'imgUrl');

            $groupdetail->group = $group;

            $users = $this->getGroupusers(input('post.unigroupId'),$groupdetail->originator);
            $Groupcounts = 0;
            foreach ($users as $value){
                $Groupcounts += (int)$value['order_count'];
            }
            $groupdetail->users = $users;
            $groupdetail->groupcounts = $Groupcounts;
            return show(config('status.SUCCESS_STATUS'),'ok',$groupdetail);
        }
    }

    private function getGroupusers($unigroupId,$originator){
        $GroupdetailModel = new Groupdetail();
        $Groupdetail = $GroupdetailModel->where(['unigroupId'=>$unigroupId,'isActive'=>1])->select();
        $userIDS = [];
        foreach ($Groupdetail as $value){
            array_push($userIDS,$value['userId']);
        }
        $users = User::all($userIDS);
        foreach ($users as &$v){
            if($v['id'] == $originator){
                $v['isHeaderGroup'] = 1;
            }
            $order = \app\common\model\Order::where(['createUser'=>$v['id'],'userSpellGroupId'=>$unigroupId])->find();
            if($order){
                $v['order_count'] = $order->total_count;
            }else{
                $v['order_count'] = 0;
            }

        }

        return $users;
    }


    /**
     * 批量更新失败的团
     * 计划任务每隔一段时间访问该接口
     * 后期需要优化，redis队列
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function groupFail(){
        $Groupdetail = new Groupdetail();
        $time = time();
        $groupListFail = $Groupdetail->where(['status'=>1,'isActive'=>1])->where('endDate','<=',$time)->select();
        if($groupListFail){
            foreach ($groupListFail as $value){
                $group = Groupproduct::get($value->groupId);
                $value->groupproduct = $group;
            }
            $GroupRefund = new GroupRefund();
            $GroupRefund->grouprefund($groupListFail);
        }
    }

}